package itsm.isperp.module.controller.incident;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.dto.project.ProjectDomain;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.utils.AnalysisQueryUtils;
import itsm.isperp.module.utils.ProjectDomainUtils;
import itsm.isperp.report.Counter;
import itsm.isperp.report.data.warehouse.QueryRequest;
import itsm.isperp.report.resolver.DataResolverUtils;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("incident/search")
public class IcdIncidentSearchController {

  @Autowired
  protected IcdIncidentService icdIncidentService;

  @Autowired
  protected AppDictService appDictService;

  @Autowired
  protected ProjProjectService projProjectService;

  @Autowired
  protected CusCustomerService cusCustomerService;

  @Autowired
  protected AppUserService appUserService;

  /**
   * 搜索页面
   * 
   * @return
   */
  @RequestMapping(value = { "manage", "manageView", "" })
  public ModelAndView manage(String projectId) {
    ModelAndView mv = new ModelAndView("incident/search/manage");

    int dataRange = ProjectDomainUtils.getUserMaxDataRange();
    mv.addObject("dataRange", dataRange);

    // 优先级
    mv.addObject("var_priority", appDictService.findByType("INCIDENT_PRIORITY"));
    mv.addObject("var_source", appDictService.findByType("INCIDENT_SOURCE"));

    // 解决方式
    mv.addObject("var_solutionWay",
        appDictService.findByType("INCIDENT_SOLUTIONWAY"));

    // 关闭码
    mv.addObject("var_closeCode",
        appDictService.findByType("INCIDENT_CLOSECODE"));

    // 事件状态
    mv.addObject("event_status", appDictService.findByType("INCIDENT_STATUS"));

    mv.addObject("event_nature", appDictService.findByType("INCIDENT_NATURE"));

    List<ProjProject> listProject=null;
    if(dataRange!=22 && dataRange!=33)
    {
      listProject = projProjectService.findAll(
          new JqGridRequest().isPageable(false).setSelectColumns("id", "name"))
          .getContent();
    }else
    {
      IUser user=ContextHolder.getLoginUser();
      JqGridRequest req = new JqGridRequest();
      req.isPageable(false);
      req.setSelectColumns("id", "name", "cus_customer_id");
      req.setSearchString(" cus_customer_id in(select customer_id from app_user where id='"+user.getId()+"')");
      listProject=projProjectService.findAll(req);
    }
    

    mv.addObject("projects", listProject);

    return mv;
  }

  @RequestMapping("extendSearchManage")
  public ModelAndView extendSearchManage(String projectId) {
    ModelAndView mv = new ModelAndView("incident/search/extendSearchManage");

    // 优先级
    mv.addObject("var_priority", appDictService.findByType("INCIDENT_PRIORITY"));
    mv.addObject("var_source", appDictService.findByType("INCIDENT_SOURCE"));

    // 解决方式
    mv.addObject("var_solutionWay",
        appDictService.findByType("INCIDENT_SOLUTIONWAY"));

    // 关闭码
    mv.addObject("var_closeCode",
        appDictService.findByType("INCIDENT_CLOSECODE"));

    // 事件状态
    mv.addObject("event_status", appDictService.findByType("INCIDENT_STATUS"));

    mv.addObject("event_nature", appDictService.findByType("INCIDENT_NATURE"));

    mv.addObject(
        "projects",
        projProjectService.findAll(
            new JqGridRequest().isPageable(false)
                .setSelectColumns("id", "name")).getContent());

    return mv;
  }

  /**
   * 根据分页器获取实体列表的json格式数据
   * 
   * @param request
   *          {@link JqGridRequest} jqGrid数据请求（查询条件、排序）
   * @param req
   *          {@link HttpServletRequest} http请求
   * @return json格式数据
   */
  @RequestMapping("list")
  @ResponseBody
  public PageResponse<Map<String, Object>> list(JqGridRequest request,
      HttpServletRequest req) {

    String projectId = req.getParameter("projectId");
    if (StringUtils.isNotEmpty(projectId)) {
      request.addFilterRule("projectId", JqGridFilterRuleOp.eq, projectId);
    }
    String ifShowExtend = req.getParameter("ifShowExtend");
    // request.addFilterRule("status", JqGridFilterRuleOp.ne, "新建");
   // request.setSearchString(" status<>'新建' ");
    if (StringUtils.isNotEmpty(ifShowExtend) && ifShowExtend.equals("1")) {
      String categoryId = req.getParameter("categoryId");
      return this.icdIncidentService.findIncidentWithPropertyMapByRequest(
          categoryId, request);
    }
    PageResponse<Map<String, Object>> p = this.icdIncidentService
        .findIncidentTotalByRequest(request);
    return p;
  }

  @RequestMapping("listExtend")
  @ResponseBody
  public PageResponse<Map<String, Object>> listExtend(JqGridRequest request,
      HttpServletRequest req) {

    String projectId = req.getParameter("projectId");
    if (StringUtils.isNotEmpty(projectId)) {
      request.addFilterRule("projectId", JqGridFilterRuleOp.eq, projectId);
    }
    String ifShowExtend = req.getParameter("ifShowExtend");
    if (ifShowExtend.equals("true")) {
      String categoryId = req.getParameter("categoryId");
      return this.icdIncidentService.findIncidentWithPropertyMapByRequest(
          categoryId, request);
    }
    PageResponse<Map<String, Object>> p = this.icdIncidentService
        .searchAllByFilter(request);
    return p;
  }

  @RequestMapping(value = { "analysis" })
  public ModelAndView analysis(JqGridRequest req, HttpServletRequest request) {
    ModelAndView mv = new ModelAndView("incident/search/analysis");
    String showBtn = "1";
    int dataRange = ProjectDomainUtils.getUserMaxDataRange();
    if (dataRange == 22 || dataRange == 33)
      showBtn = "0";
    mv.addObject("showBtn", showBtn);
    return mv;
  }

  @RequestMapping(value = { "analysis2" })
  public ModelAndView analysis2(JqGridRequest req, HttpServletRequest request) {
    ModelAndView mv = new ModelAndView("incident/search/analysis2");

    return mv;
  }

  @RequestMapping(value = { "analysisList" })
  @ResponseBody
  public PageResponse<Map<String, Object>> analysisList(JqGridRequest request,
      HttpServletRequest req) {

    String projectId = req.getParameter("projectId");
    if (StringUtils.isNotEmpty(projectId)) {
      request.addFilterRule("projectId", JqGridFilterRuleOp.eq, projectId);
    }
    StringBuilder sb = new StringBuilder();

    AnalysisQueryUtils.buildAnalysisQuery(1, sb, req);

    request.setSearchString(" 1=1 " + sb.toString());

    // request.addFilterRule("status", JqGridFilterRuleOp.ne, "已关闭");
    request.setProjectDomain(ProjectDomain.newInstance());
    PageResponse<Map<String, Object>> p = this.icdIncidentService
        .findAllDetailByRequest(request).toPage();

    return p;
  }

  @RequestMapping(value = { "reloadQueryPanelData" })
  @ResponseBody
  public Map<String, Map<String, Counter>> reloadQueryPanelData(
      JqGridRequest request, HttpServletRequest req) {

    StringBuilder sb = new StringBuilder();
    // Set<String> fields = new HashSet<>();
    // fields.add("confirmtimeman_name");
    // fields.add("supporter_name");
    // fields.add("incident_type");
    // fields.add("priority_name");
    // fields.add("status");
    // fields.add("sla_status");
    AnalysisQueryUtils.buildAnalysisQuery(1, sb, req);

    QueryRequest qr = new QueryRequest();
    // qr.addColumn("confirmtimeman_name");
    qr.addColumn("supporter_name");
    qr.addColumn("incident_type");
    qr.addColumn("priority_name");
    qr.addColumn("status");
    qr.addColumn("sla_status");
    qr.addColumn("cus_user_name");

    qr.setFrom("icd_incident_total");
    qr.setWhere(sb.toString()
    // + " AND status<>'已关闭'"
        + ProjectDomainUtils.getUserDomainSql(ProjectDomain.newInstance()));

    Map<String, Map<String, Counter>> map = DataResolverUtils.resolve(qr);

    return map;
  }

}
